/**
 * 点击详情
 * @param warningEventId   告警事件id
 */

var modalHtml="";
$(function(){
    modalHtml=$("#modalDetailsAlarm").html();
});



//获取详细信息
function getrepor(result){
    var details ="";
    $("#detailsgoods").text(result.bean.goods);
    $("#detailsnum").text(result.bean.num);
    $("#detailstype").text(result.bean.busiType);
    $("#detailsreportId").text(result.bean.reportId);
    $("#detailsposition").text(result.bean.position);
    $("#detailsuser").text(result.bean.reportUserName);
    $("#detailsphone").text(result.bean.reportUserPhone);
    $("#detailsreprotDesc").text(result.bean.reportDesc);
    if(result.bean.status == 1){
        var status = "已处理";

    }
    else{
        var status = "未处理";

        if(order==1){
            details = "<li class='width-all' style='padding: 0;'> <label>反馈内容：</label> <textarea id='replyMsg' cols='50' maxlength='200' style='resize: none'></textarea></li>" +
                "<li class='width-all' style='padding: 0;'> <a class='t-btn t-btn-sm t-btn-blue t-btn-deal t-btn-blue-order'id='btnorder'>确认反馈</a></li>" ;
        }
        else if(order==0){
            details ="";
        }
    }
    $("#detailsstatus").text(status);
    if(result.bean.status == 1){
        details = "<li class='width-all' style='padding: 0;'> <label>管理员　：</label> <div id='detailsreplyUserName'>"+result.bean.replyUserName +"</div></li>" +
                      "<li class='width-all' style='padding: 0;'> <label>反馈内容：</label> <div id='detailsreplyMsg'>"+result.bean.replyMsg +"</div></li>" +
                     "<li class='width-all' style='padding: 0;'> <label>反馈时间：</label> <div id='detailsreplyTime'>"+result.bean.replyTime +"</div></li>" ;

    }
    $("#detailshide").html(details);
    $("#modalDetailsAlarm").modal({
        keyboard: true,
        backdrop: 'static'
    }).on('show.bs.modal', centerModal());
    $(window).on('resize', centerModal());
}
function detailSelect(userphone){
    order = 0;
    $(".modal-title").text("报修详情");
    // PostForm("/cwp/front/sh/repair!execute","uid=R003&reportId="+userphone,"",getrepor,"");

    $.getJSON('/cwp/src/json/repair/repair_bangong_r003_info.json',function(data){
        getrepor(data);
    })

}
//审核
$(document).on("click","#btnorder", function () {
        if ($("#replyMsg").val()!="") {
            // $.ajax({
            //     url:'/cwp/front/sh/repair!execute',
            //     beforeSend:function(requests){
            //         requests.setRequestHeader("platform", "pc");
            //     },
            //     data:{
            //         uid:'R005',
            //         replyUserId:userId,
            //         reportId:$("#detailsreportId").text(),
            //         reportUserId:$("#detailsuser").text(),
            //         goods:$("#detailsgoods").text(),
            //         num:$("#detailsnum").text(),
            //         busiType:$("#busiType").val(),
            //         position: $("#detailsposition").text(),
            //         reprotDesc:$("#detailsreprotDesc").text(),
            //         busiType:$("#detailstype").text(),
            //         status:1,
            //         replyMsg:$("#replyMsg").val()
            //     },
            //     type:'post',
            //     success:function (res) {
            //         if(res.returnCode == '0'){
            //             tipModal("icon-checkmark", "反馈成功");
            //             isPostBack=true;
            //             getrepair(1);
            //         }else{
            //             tipModal("icon-cross", "反馈失败");
            //         }
            //
            //     },
            //     error:function () {
            //         _self.removeAttr('disabled');
            //         _self.text('保存')
            //     }
            // })
            $.getJSON('/cwp/src/json/repair/repair_r005.json',function(data){
                saveWarningEventResultArrived(data);
            })
            $("#modalDetailsAlarm").modal("hide");
        }
        else{
            tipModal("icon-cross", "提交内容不能为空");
        }

});
var order = 0;
function repairord(userphone){
    order = 1;
    $(".modal-title").text("报修反馈");
    // PostForm("/cwp/front/sh/repair!execute","uid=R003&reportId="+userphone,"",getrepor,"");

    $.getJSON('/cwp/src/json/repair/repair_bangong_r003_fk.json',function(data){
        getrepor(data);
    })

}
//切换分类
var busiType=0;
$("#myTabs li").on("click", function () {
    busiType=$(this).index();
    $(".bg-date").val("");
    isPostBack=true;
    getrepair(1);

});
//查询
$("#btnSearchFaultAlarm").on("click",function(){
    isPostBack=true;
    getrepair(1);
});
//获取所有报修信息
function getrepair(pageIndex){
    var startReportTime = $("#startApplyTime").val();
    var endReportTime = $("#endApplyTime").val();
    if("undefined" == typeof startReportTime){
        startReportTime="";
    }
    if("undefined" == typeof endReportTime){
        endReportTime="";
    }

    var hUrl = busiType == 0?'/cwp/src/json/repair/repair_bangong_r002.json':'/cwp/src/json/repair/repair_gongg_r002.json';

    $.getJSON(hUrl,function(data){

        // var dTemp = JSON.parse(data);
        var loaderRealtyTab = new LoaderTable("faultAlarmLoader","faultAlarmTab","/cwp/front/sh/repair!execute","uid=R002&busiType="+busiType+"&startReportTime="+ startReportTime +"&endReportTime="+endReportTime,pageIndex,8,repair,"");
        // loaderRealtyTab.Display();
        loaderRealtyTab.loadSuccessed(data);
    });

}

function paginationCallback(page_index){
    if(!isPostBack) getrepair(page_index+1);
}

function repair(result){
    var thead="<thead>"+
        "<tr>"+
        "<th>姓名</th>"+
        "<th>维修物品</th>"+
        "<th>维修地址</th>"+
        //"<th>详细描述</th>"+
        "<th>联系方式</th>"+
        "<th>提交时间</th>"+
        "<th>流程状态</th>"+
        "<th class='unBind'>操作</th>"+
        "</tr>"+
        "</thead>";
    var tbodys= "<tbody>";
    for(var i=0;i<result.beans.length;i++) {
        if(result.beans[i].status == 1){
            var string = "已处理";
            var pepairbtn = "<a class='t-btn t-btn-sm t-btn-disabled t-btn-deal'>反馈</a>";
        }
        else{
            var string = "未处理";
            var pepairbtn = "<a class='t-btn t-btn-sm t-btn-red t-btn-deal' onclick='repairord("+result.beans[i].reportId+")'>反馈</a>";
        }
        tbodys += "<tr>" +
            "<td>" +  result.beans[i].reportUserName + "</td>" +
            "<td>" +  result.beans[i].goods + "</td>" +
            "<td>" +  result.beans[i].position + "</td>" +
            //"<td class='table-overflow'>" +  result.beans[i].reportDesc + "</td>" +
            "<td>" +  result.beans[i].reportUserPhone + "</td>" +
            "<td>" +  result.beans[i].reportTime + "</td>" +
            "<td>" +  string + "</td>" +
            "<td><a class='t-btn t-btn-sm t-btn-blue t-btn-deal' onclick='detailSelect("+result.beans[i].reportId+")'>详情</a>"+pepairbtn+"</td>" +
            "</tr>"
    }
    tbodys+= "</tbody>";
    $("#faultAlarmTab").html(thead+tbodys);

}
getrepair(1);

//新增类别
function AddWarningDictionarytResultArrived(result){
    var sel = $("#busiType");
    var option = "";
    sel.empty();
    option = $("<option>").text("请选择").val("");
    sel.append(option);
    option = $("<option>").text("办公用品").val(0);
    sel.append(option);
    option = $("<option>").text("公共设施").val(1);
    sel.append(option);
}
//新增验证
function eventValidtor()
{
    $.formValidator.initConfig({
        formid: "frmMain", onerror: function (msg) {
            return false;
        }, onsuccess: function () {
            return true;
        }
    });

    $("#reprotDesc").formValidator({
        onfocus: "请输入故障描述",
        oncorrect: " "
    }).InputValidator({
        min:4,
        max: 100,
        onempty: "请输入故障描述",
        onerror: "描述长度为4-100个字符"
    });

    $("#busiType").formValidator({
        onfocus:"请选择设备类别",
        oncorrect:"&nbsp;"
    }).InputValidator({
        min:1,
        onempty:"请选择设备类别",
        onerror: "请选择设备类别"
    });

    $("#position").formValidator({
        onfocus: "请输入报修位置",
        oncorrect: " "
    }).InputValidator({
        min:1,
        max: 100,
        onempty: "请输入报修位置",
        onerror: "描述长度为4-100个字符"
    });

    $("#num").formValidator({
        onfocus: "请输入报修数量",
        oncorrect: " "
    }).InputValidator({
        min:1,
        max: 100,
        onempty: "请输入报修数量",
        onerror: "描述长度为4-100个字符"
    }).RegexValidator({
        regexp:"num",
        datatype: "enum",
        onerror: "请输入正确的数量"
    });

    $("#goods").formValidator({
        onfocus: "请输入报物品",
        oncorrect: " "
    }).InputValidator({
        min:1,
        max: 100,
        onempty: "请输入报物品",
        onerror: "描述长度为4-100个字符"
    });
}
/*
 * post提交数据
 * 发送地址，uid，action行为，成功回调函数，失败回调函数
 *@author cheqniuxu
 *@created 2016/05/31
 *通过字典表查询字典数据表告警类别
 * */

$(function() {
    warningDictionaryType();
    //验证
    eventValidtor();
});
function warningDictionaryType(){
    PostForm("/cwp/front/sh/warningEvent!execute", "uid=c002_3&dictKey=intelligentType&dictdataKey='security','building_services'", "", WarningDictionarytResultArrived, '');
}

function WarningDictionarytResultArrived(result){
    var sel = $("#diName");
    var option = ""
    sel.empty();
    option = $("<option>").text("请选择").val("");
    sel.append(option);
    for ( var i = 0; i <   result.beans.length; i++) {
        option = $("<option>").text(result.beans[i].deviceName).val(result.beans[i].dictdataValue);
        sel.append(option);
    }
}

//-----------------新增开始--------------------------//
function addWarningDictionaryType(){
    PostForm("/cwp/front/sh/warningEvent!execute", "uid=c002_3&dictKey=intelligentType&dictdataKey='security','building_services'", "", AddWarningDictionarytResultArrived, '');
}
var userId = localStorage.getItem("parkId");
//添加日常报修
function saveWarningEvent() {
    //判断表单验证是否通过
    if ($.formValidator.PageIsValid()) {
        $.ajax({
            url:'/cwp/front/sh/repair!execute',
            beforeSend:function(requests){
                requests.setRequestHeader("platform", "pc");
            },
            data:{
                uid:'R001',
                reportUserId:userId,
                goods:$("#goods").val(),
                num:$("#num").val(),
                busiType:$("#busiType").val(),
                position: $("#position").val(),
                reprotDesc:$("#reprotDesc").val(),
            },
            type:'get',
            success:function (res) {
                if(res.returnCode == '0'){
                    tipModal("icon-checkmark", "添加成功");
                }else{
                    tipModal("icon-cross", "添加失败");
                }
            },
            error:function () {
                _self.removeAttr('disabled');
                _self.text('保存')
            }
        })
        //关闭模态框
        $("#modalMaintenanceNew").modal("hide");
    }
}


function saveWarningEventResultArrived(result){
    switch (result.returnCode) {
        case "0":
            tipModal("icon-checkmark", "添加成功");
            isPostBack=true;
            // faultAlarmList(1);
            break;
        case "2":
            tipModal("icon-cross", "添加失败");
            break;
        case "-9999":
            tipModal("icon-cross", "添加失败");
            break;
    }
}
////绑定点击事件
//新建
$("#btnMaintenanceNew").on("click", function () {
    //告警类型
    addWarningDictionaryType();
    $("#modalMaintenanceNew").modal({
        keyboard: true,
        backdrop: 'static'
    }).on('show.bs.modal', centerModal());
    $(window).on('resize', centerModal());
});
//-------------新增结束---------------------//


